﻿using System;
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace KL.Store.Core.Ucuzu
{
    public class TrustedShop
    {
        private const string ServiceHost = "www.ucuzu.com";
        private const string ServiceUrl = "/affiliation/TrustedShop.php";
        private const string ErrorEmail = "Lütfen müşteri email adresini belirtin!";
        private const string ErrorService = "Müşteri bilgileri kayıt edilemedi.";
        private string _webApiKey;
        private string _email;
        private string _protocol;

        private List<string> _products = new List<string>();
        public TrustedShop(string WebApiKey)
        {
            this._webApiKey = WebApiKey;
            this._protocol = HttpContext.Current.Request.Url.Scheme;
        }

        public void SetEmail(string email)
        {
            this._email = email;
        }

        public void AddProduct(string productname)
        {
            this._products.Add(productname);
        }

        public string Send()
        {
            if (string.IsNullOrEmpty(this._email))
                throw new Exception(ErrorEmail);

            string str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            string C = "";
            Random RandomClass = new Random();
            for (int i = 0; i <= 19; i++)
            {
                C += str.Substring(RandomClass.Next(0, str.Length - 1), 1);
            }

            long timestamp = misc.UnixTimeNow();

            string HashedKey = misc.GetMD5(_webApiKey + timestamp.ToString());

            string query = "HashedKey=" + HashedKey + "&Email=" + Uri.EscapeUriString(_email);

            foreach (string p_loopVariable in _products)
            {
                string p = p_loopVariable;
                query += "&Products[]=" + Uri.EscapeUriString(p);
            }

            query += "&Timestamp=" + timestamp.ToString();

            string res = null;
            res = "<script type=\"text/javascript\" src=\"" + _protocol + "://" + ServiceHost + "/fc.js\"></script>"
                + "<script type=\"text/javascript\">"
                + "function fc_request_done(C) { var I = new Image(); "
                + "I.src='" + _protocol + "://" + ServiceHost + ServiceUrl + "?" + query + "&C='+C; }"
                + "set_fc(\"" + TrustedShop.ServiceHost + "\", \"__aku\",\"" + C + "\");"
                + "</script>"
                + "<noscript>" + "<img src=\"" + _protocol + "://" + ServiceHost + ServiceUrl + "?" + query + "&C=" + C + "\">" + "</noscript>" + Environment.NewLine;

            return res;
        }

    }

    static class misc
    {

        public static long UnixTimeNow()
        {
            TimeSpan _TimeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0);
            return Convert.ToInt64(_TimeSpan.TotalSeconds);
        }

        public static string GetMD5(string SourceText)
        {
            byte[] textBytes = System.Text.Encoding.Default.GetBytes(SourceText);
            try
            {
                MD5CryptoServiceProvider cryptHandler = null;
                cryptHandler = new MD5CryptoServiceProvider();
                byte[] hash = cryptHandler.ComputeHash(textBytes);
                string ret = "";
                foreach (byte a in hash)
                {
                    if (a < 16)
                    {
                        ret += "0" + a.ToString("x");
                    }
                    else
                    {
                        ret += a.ToString("x");
                    }
                }
                return ret;
            }
            catch
            {
                throw;
            }
        }
    }
}
